<?php
require_once("ErrCode.php");
require "functions.php";
class User
{
	private $_db ;
	public function __construct($db)
	{
		$this->_db = $db ;
	}
	public function login($username,$password){
		if(empty($username)){
			throw new Exception("用户名不能为空",ErrCode::USERNAME_CONNOT_EMPTY);
		}
		if(empty($password)){
			throw new Exception("密码不能为空",ErrCode::PASSWORD_EMPTY);
		}
		$password = md5str($password);
		$sql = "SELECT * FROM `user` WHERE `username`=:username AND `password`=:password ";
		$stmt = $this->_db->prepare($sql);
		$stmt->bindParam(":username",$username);
		$stmt->bindParam(":password",$password);
		$stmt->execute();
		$user = $stmt->fetch(PDO::FETCH_ASSOC);
		if(empty($user)){
			throw new Exception("密码或密码错误",ErrCode::PASSWORD_ERROR);
		}else{
			unset($user['password']);
			return $user;
		}
	}
	public function register($username,$password){
		if(empty($username)){
			throw new Exception("用户名不能为空",ErrCode::USERNAME_CONNOT_EMPTY);
		}
		if(empty($password)){
			throw new Exception("密码不能为空",ErrCode::PASSWORD_EMPTY);
		}
		if($this->_isUserNameExsit($username)){
			throw new Exception("用户名已存在",ErrCode::USERNAME_EXIST);
		}
		//写入数据库
		$create_time = Date("Y-m-d H:i:s",time());
		$password = md5str($password);
		$sql = "INSERT INTO `user`(`username`,`password`,`create_time`) VALUE(:username,:password,:create_time)";
		$stmt = $this->_db->prepare($sql);
		$stmt->bindParam(":username",$username);
		$stmt->bindParam(":password",$password);
		$stmt->bindParam(":create_time",$create_time);
		if(!$stmt->execute()){
			throw new Exception("用户注册失败",ErrCode::REGISTER_FAIL);
		}
		return [
			'userId' => $this->_db->lastInsertId(),
			'username' => $username ,
			'create_time' => $create_time
		];
	}
	private function _isUserNameExsit($username){
		$exsit = false ;
		//预处理语句
		$sql = "select * from `user` where `username`=:username";
		$stmt = $this->_db->prepare($sql);
		//绑定变量
		$stmt->bindParam(':username', $username);
		//执行查询
		$stmt->execute();	
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		return !empty($result) ;
	}
}